#include <iostream>

using namespace std;

/* ---- 入门版本 ------------------------------------
 * 会有内存泄露问题. 因为在实际执行时会发现, 析构函数没有
 * 被调用, 所以, 如果在单例模式中有申请别的资源,那么在程
 * 序结束时资源是不会被正确释放的
 */
class AAA {
    static AAA *p;
public:
    static AAA *getInstence() {
        if (p == NULL) p = new AAA();
        return p;
    }
    ~AAA(){
        cout << "I am released." << endl;
    }
private:
    AAA(){}
};

AAA *AAA::p = NULL;

/* ---- 入门版本的补救版本 -------------------------------
 */
class BBB {
    static BBB *p;
public:
    static BBB *getInstence() {
        if (p == NULL) p = new BBB();
        return p;
    }
    ~BBB(){
        cout << "I am released." << endl;
    }
private:
    class Deleter {
    public:
        ~Deleter(){
            cout << "I am invoked" << endl;
            if (BBB::p != NULL) 
                delete BBB::p;
        }
    };
    static Deleter del;
private:
    BBB(){}
};

BBB *BBB::p = NULL;

int main(int argc, char const *argv[])
{
    {
        AAA *pa, *pb;
        pa = AAA::getInstence();
        pb = AAA::getInstence();
        cout << "pa = " << pa << endl;
        cout << "pb = " << pb << endl;
    }
    

    // ------------------------------

    {
        BBB *pa, *pb;
        pa = BBB::getInstence();
        pb = BBB::getInstence();
        cout << "pa = " << pa << endl;
        cout << "pb = " << pb << endl;
    }

    return 0;
}


